package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.server.WebSocketServer;
import com.sky.service.OrdersService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShopingCartMapper shoppingCartMapper;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submitOrders(OrdersSubmitDTO ordersSubmitDTO) {
        //意外一：没有地址
        //根据地址id查询地址
        AddressBook addressBook = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //意外二：购物车没数据
        //根据用户id查询购物车
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findByUserId(userId);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1.添加orders表
        Orders orders = new Orders();
        //把数据拷贝的orders
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        //设置11个属性
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        orders.setStatus(Orders.PENDING_PAYMENT);//未下单1
        orders.setUserId(userId);//用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//未支付

        User user = userMapper.findByid(userId);
        orders.setUserName(user.getName());//用户名-》user表中的用户名

        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//手机号

        //地址->手动拼接 省+市+区+详细地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //保存orders
        ordersMapper.saveOrder(orders);

        //2.添加orders_details
        shoppingCarts.forEach(shoppingCart -> {
            //订单详情
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setId(null);
            //设置order的id
            orderDetail.setOrderId(orders.getId());
            //把每一个订单详情保存的数据库中
            orderDetailMapper.saveOrderDetail(orderDetail);
        });

        //3.清空购物车
        shoppingCartMapper.clean(userId);

        OrderSubmitVO vo = OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime()).build();

        return vo;
    }

    @Override
    public void paySuccess(String orderNum) {
        //1.查询订单 => 订单号
        //?思考?如果在这里我们想要获取用户的id我们可以怎么操作?
        //站在后台和微信的角度去考虑
        Orders orderDB = ordersMapper.findOrderByNum(orderNum);
        //2.修改订单的状态
        ordersMapper.update(
                Orders.builder()
                        .id(orderDB.getId())
                        .status(Orders.TO_BE_CONFIRMED)
                        .payStatus(Orders.PAID)
                        .checkoutTime(LocalDateTime.now())
                        .build()
        );
    }

    @Override
    public void deliveryOrders(Long id) {
        Orders orders = ordersMapper.findOrderById(id);
        ordersMapper.update(
                Orders.builder()
                        .id(orders.getId())
                        .status(Orders.DELIVERY_IN_PROGRESS)
                        .build()

        );
    }


    @Override
    public OrderStatisticsVO statistics() {
        List<Orders> list = ordersMapper.findAll();
        Integer confirmed = 0;
        Integer deliveryInProgress = 0;
        Integer toBeConfirmed = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getStatus() == 2) {
                toBeConfirmed = toBeConfirmed + 1;
            } else if (list.get(i).getStatus() == 3) {
                confirmed = confirmed + 1;
            } else if (list.get(i).getStatus() == 4) {
                deliveryInProgress = deliveryInProgress + 1;
            }
        }
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void CancellationOfOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }


    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findOrderDetail(Long id) {
        Orders orders = ordersMapper.findOrderById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.findOrderDetailList(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 再来一单功能
     *
     * @param id
     */
    @Override
    public void OneMoreOrder(Long id) {
        List<OrderDetail> list = orderDetailMapper.findOrderDetailList(id);
        Long userId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        list.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(now);
            shoppingCartMapper.save(shoppingCart);
        });
    }

    /**
     * 接单
     *
     * @param id
     */
    @Override
    public void receiving(Long id) {
        ordersMapper.update(Orders.builder()
                .id(id)
                .status(Orders.CONFIRMED)
                .build());
    }

    /**
     * 拒单
     *
     * @param dto
     */
    @Override
    public void reject(OrdersRejectionDTO dto) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        BeanUtils.copyProperties(dto, orders);
        ordersMapper.update(orders);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<Orders> ordersList = ordersMapper.findByMultiple(ordersPageQueryDTO);
        ordersList.forEach(
                orders -> {
                    String str = "";
                    //根据id查询出菜品信息
                    List<OrderDetail> detailList = orderDetailMapper.findByOrderId(orders.getId());
                    for (OrderDetail detail : detailList) {
                        String detailName = detail.getName();
                        String dishFlavor = detail.getDishFlavor();
                        OrderDetail orderDetail = new OrderDetail();
                        orderDetail.setName(detailName);
                        orderDetail.setDishFlavor(dishFlavor);
                        orderDetail.setOrderId(orders.getId());
                        Integer count = orderDetailMapper.findByNameAndFlavorCount(orderDetail);
                        str += detailName + "*" + count + ";";
                    }
                    orders.setOrderDishes(str);
                }
        );
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        return new PageResult(pageInfo.getTotal(), ordersList);
    }

    /**
     * 查看历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageHistory(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Long userId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setUserId(userId);
        BeanUtils.copyProperties(ordersPageQueryDTO, orders);
        List<Orders> orderVOList = ordersMapper.getAllByOrders(orders);
        List<OrderVO> orderVOS = orderVOList.stream().map(orderss -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orderss, orderVO);
            List<OrderDetail> orderDetailList = orderDetailMapper.getAllByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
            return orderVO;
        }).collect(Collectors.toList());
        PageInfo<OrderVO> orderVOPage = new PageInfo<>(orderVOS);
        return new PageResult(orderVOPage.getTotal(), orderVOS);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        ordersMapper.update(
                Orders.builder()
                        .id(id)
                        .status(Orders.COMPLETED)
                        .deliveryTime(LocalDateTime.now())
                        .build());
    }

    @Override
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        ordersMapper.update(orders);

        Orders orderDB = ordersMapper.findOrderByNum(ordersPaymentDTO.getOrderNumber());

        HashMap<String, Object> parms = new HashMap<>();
        parms.put("type",1);
        parms.put("orderId",orderDB.getId());
        parms.put("content","订单号："+orderDB.getNumber());
        String jsonResult = JSONObject.toJSONString(parms);
        webSocketServer.sendToAllClient(jsonResult);
    }

    @Override
    public void cancelItem(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }
}
